package com.share.beta.feign.outapi.config;

import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.EncodeException;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;

@Slf4j
@Configuration
public class OutFeignConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    //实例化-加密对象----get请求不走这里
    @Bean
    public SpringFormEncoder springFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters) {
            //requestBody 方法的请求参数
            //bodytype  方法的请求参数的数据类型
            @Override
            public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
                //基础参数获取
                String url = request.url();
                String method = request.method();
                Collection<String> ct = request.headers().get("Content-Type");
                MediaType mediaType = CollectionUtils.isEmpty(ct) ? null : MediaType.valueOf(ct.iterator().next());//参数可能为空

                if ("GET".equalsIgnoreCase(method)) {

                } else if ("POST".equalsIgnoreCase(method)) {

                } else {
                    log.error("请求不支持");
                }

                //打印解密前的数据
                String str = JSON.toJSONString(requestBody);
                log.info("url={},加密前的数据str={}", url, str);

                //执行加密
                String enStr = "{\"code\":\"0\",\"data\":\"Fasfasfdaaaaaaaaaaaaaaaaaaaaaaadfasdf\"}";

                Object enObj = JSON.parseObject(enStr);

                super.encode(enObj, Object.class, request);
            }
        });
    }

    //实例化-解密对象
    @Bean
    public SpringDecoder springDecoder() {
        return new SpringDecoder(messageConverters) {
            // Type type 是方法返回的数据类型
            @Override
            public Object decode(Response response, Type type) throws IOException, FeignException {
                String enstr = (String) super.decode(response, String.class);
                log.info("响应返回待解密字符串enstr={}", enstr);

                //执行解密操作
                String str = "{\"code\":\"0\",\"data\":\"解密\"}";

                return JSON.parseObject(str, type);
            }
        };
    }
}
